package com.atguigu.srb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.srb.oss.service.FileService;
import com.atguigu.srb.oss.utils.OssProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Override//上传文件到阿里云
    public String upload(InputStream inputStream, String module, String fileName) {
        //创建oss实例
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET
        );
        //判断oss实例是否存在，如果不存在，则获取
        if (!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)){
            //创建bucket
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }
        //构建日期路径：avator/2022/12/24/文件名
        String folder = new DateTime().toString("yyyy/MM/dd");
        //文件名:uuid.扩展名
        fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        //文件根路径
        String key=module+"/"+folder+"/"+fileName;
        //文件上传到阿里云
        ossClient.putObject(OssProperties.BUCKET_NAME,key,inputStream);
        //关闭ossclient
        ossClient.shutdown();
        return "https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/"+key;
    }

    @Override//根据路径删除文件
    public void removeFile(String url) {
        //创建oss实例
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET
        );
        //文件名（服务器上的文件路径）
        String host="https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/";
        String objectName = url.substring(host.length());
        //删除文件
        ossClient.deleteObject(OssProperties.BUCKET_NAME,objectName);
        //关闭ossClient
        ossClient.shutdown();
    }
}
